<template>
  <el-dialog
    title="图片裁剪"
    top="12px"
    :visible.sync="dialogVisible"
    width="80%"
    :show-close="false"
    :close-on-click-modal="false"
    append-to-body
  >
    <!-- cropper -->
    <div class="cropper-contanier">
      <vue-cropper
        ref="cropper"
        :mode="option.mode"
        :img="option.img"
        :output-size="option.outputSize"
        :output-type="option.outputType"
        :info="option.info"
        :full="option.full"
        :fixed="option.fixed"
        :fixed-number="option.fixedNumber"
        :can-move="option.canMove"
        :can-move-box="option.canMoveBox"
        :fixed-box="option.fixedBox"
        :original="option.original"
        :auto-crop="option.autoCrop"
        :auto-crop-width="option.autoCropWidth"
        :auto-crop-height="option.autoCropHeight"
        :center-box="option.centerBox"
        :high="option.high"
        :max-img-size="option.maxImgSize"
        @img-load="imgLoad"
        @crop-moving="cropMoving"
      ></vue-cropper>
    </div>
    <div class="mt-4">
      <el-row type="flex" align="center" :gutter="24">
        <el-col class="text-right">
          <el-upload
            ref="upload"
            action="/"
            :on-change="onChange"
            accept="image/png, image/jpeg, image/jpg"
            :show-file-list="false"
            :auto-upload="false"
          >
            <el-button slot="trigger" size="small" type="primary" ref="uploadBtn"> 选择图片 </el-button>
          </el-upload>
          <div>支持jpg、png格式的图片，大小不超过5M</div>
        </el-col>
        <el-col>
          <el-button type="primary" @click="changeScale(1)">放大 </el-button>
          <el-button type="primary" @click="changeScale(-1)">缩小</el-button>
          <el-button type="primary" @click="rotateLeft">向左转</el-button>
          <el-button type="primary" @click="rotateRight">向右转</el-button></el-col
        >
      </el-row>
    </div>

    <div slot="footer" class="text-center">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="handleSave">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { VueCropper } from 'vue-cropper';
import { uploadApi } from '@/api/upload-api';
import { updateAvatarApi } from '@/api/user-api';
// 裁剪生成图片的格式
const outputType = ['jpeg', 'png', 'webp'];
export default {
  name: 'Cropper',
  props: {
    visible: {
      type: Boolean,
      require: true,
      default: false
    }
  },
  components: {
    VueCropper
  },
  data() {
    return {
      localVisible: this.visible,
      fileName: '',
      type: 'blob',
      option: {
        mode: 'cover', // 图片默认渲染方式 [contain , cover, 100px, 100% auto]
        img: '', // 裁剪图片的地址
        outputSize: 1, // 裁剪生成图片的质量
        outputType: 'png', // 裁剪生成图片的格式
        info: false, // 记录裁剪框的大小信息
        full: false, // 是否输出原图比例的截图
        canScale: true, // 图片是否允许滚轮缩放

        original: false, // 上传图片按照原始比例渲染
        canMove: false, // 上传图片是否可以移动
        canMoveBox: true, // 截图框能否拖动
        autoCrop: true, // 是否默认生成截图框
        // 只有自动截图开启 宽度高度才生效
        autoCropWidth: 750,
        autoCropHeight: 340,
        centerBox: true,
        high: true, // 是否按照设备的dpr 输出等比例图片
        maxImgSize: 2000, // 限制图片最大宽度和高度
        fixed: false, // 是否开启截图框宽高固定比例
        fixedBox: false, // 固定截图框大小 - 默认不允许改变
        fixedNumber: [16, 9] // 截图框的宽高比例
      },
      imageSrc: ''
    };
  },
  computed: {
    dialogVisible: {
      get() {
        return this.localVisible;
      },
      set(val) {
        this.$emit('update:visible', val);
      }
    }
  },
  methods: {
    handleClose() {
      this.dialogVisible = false;
    },
    handleSave() {
      this.$refs.cropper.getCropBlob(async (res) => {
        console.log(res);
        const formData = new FormData();
        formData.append('file', res, this.fileName);
        try {
          const { data } = await uploadApi(formData);
          console.log(data);

          const { code } = await updateAvatarApi({
            avatar: data
          });
          if(code === 200){
            this.$modal.msgSuccess()
            this.$emit('on-success')
            this.handleClose()
          }
        } catch (err) {
          console.warn(err);
        }
        // const img = window.URL.createObjectURL(data);
        // console.log(img);
      });
    },

    onChange(file) {
      console.log('🚀🚀 ~ upload ~ file:', file);
      const isIMAGE = file.raw.type === 'image/jpeg' || file.raw.type === 'image/png';
      const isLt5M = file.raw.size / 1024 / 1024 < 5;
      if (!isIMAGE) {
        this.$message({
          showClose: true,
          message: '请选择 jpg、png 格式的图片',
          type: 'warning'
        });
        return false;
      }
      if (!isLt5M) {
        this.$message({
          showClose: true,
          message: '图片大小不能超过 5MB',
          type: 'warning'
        });
        return false;
      }
      let reader = new FileReader();
      reader.readAsDataURL(file.raw);
      reader.onload = (e) => {
        this.option.img = e.target.result; // base64
        this.fileName = file.name;
      };
    },

    finish(type) {
      // 输出
      // var test = window.open('about:blank')
      // test.document.body.innerHTML = '图片生成中..'
      if (type === 'blob') {
        this.$refs.cropper.getCropBlob((data) => {
          console.log(data);
          var img = window.URL.createObjectURL(data);
          this.model = true;
          this.modelSrc = img;
        });
      } else {
        this.$refs.cropper.getCropData((data) => {
          this.model = true;
          this.modelSrc = data;
        });
      }
    },

    imgLoad(msg) {
      console.log(msg);
    },
    cropMoving(data) {
      console.log(data, '截图框当前坐标');
    },

    changeScale(num) {
      num = num || 1;
      this.$refs.cropper.changeScale(num);
    },
    rotateLeft() {
      this.$refs.cropper.rotateLeft();
    },
    rotateRight() {
      this.$refs.cropper.rotateRight();
    }
  }
};
</script>

<style lang="scss" scoped>
.cropper-contanier {
  width: 600px;
  height: 500px;
  margin: 24px auto;
}
.upload-btn {
  display: inline-block;
  line-height: 1;
  white-space: nowrap;
  cursor: pointer;
  background: #fff;
  border: 1px solid #c0ccda;
  color: #1f2d3d;
  text-align: center;
  box-sizing: border-box;
  outline: none;
  padding: 9px 15px;
  font-size: 12px;
  border-radius: 4px;
  color: #fff;
  background-color: #1890ff;
  border-color: #1890ff;
  transition: all 0.2s ease;
  text-decoration: none;
  user-select: none;
}
</style>
